package com.like.hospitalworld;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.like.entity.CourseInfo;
import com.like.entity.EventWrapper;
import com.like.entity.GeneralResponse;
import com.like.entity.GetCourseReq;
import com.like.entity.InfoReplyReq;
import com.like.fragment.VideoCourseDetailContentFragment;
import com.like.fragment.VideoCourseDetailReplyFragment;
import com.like.likeutils.device.KeyBoardUtils;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.InfoService;
import com.like.network.MeetingService;
import com.like.network.ResponseCode;
import com.like.network.RetrofitUtil;
import com.like.network.WindowService;
import com.like.utils.Constants;
import com.like.widget.MyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.activity_video_course_detail)
public class VideoCourseDetailActivity extends BaseActivity {

    public static final int REQUEST_VIDEO_COURSE_INFO = 100;
    public static final int REQUEST_CLOSE_COMMENT = 101;

    @ViewInject(R.id.comment_real_container)
    private ViewGroup mCommentRealContainer;
    @ViewInject(R.id.comment_container)
    private ViewGroup mCommentContainer;
    @ViewInject(R.id.edit_comment_real)
    private EditText mEditCommentReal;
    @ViewInject(R.id.edit_comment)
    private EditText mEditComment;
    @ViewInject(R.id.child_container)
    private ViewGroup mChildContainer;

    private VideoCourseDetailContentFragment mContentFragment;
    private VideoCourseDetailReplyFragment mReplyFragment;
    private InfoService mInfoService;
    private WindowService mWindowService;
    private MeetingService mMeetingService;
    private CourseInfo mCourseInfo;
    private Fragment[] mFragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInfoService = RetrofitUtil.getService(InfoService.class);
        EventBus.getDefault().register(this);
        mMeetingService = RetrofitUtil.getService(MeetingService.class);
        mWindowService = RetrofitUtil.getService(WindowService.class);
        initFragments();
        showContent();
        getCourseDetail();
        mEditComment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    openComment();
                }
            }
        });
        mEditCommentReal.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    closeComment(false);
                }
            }
        });
    }

    private void openComment() {
        mCommentContainer.setVisibility(View.GONE);
        mCommentRealContainer.setVisibility(View.VISIBLE);
        mEditCommentReal.requestFocus();
        KeyBoardUtils.openKeybord(mEditCommentReal, m.mContext);
    }

    private void closeComment(boolean clearText) {
        KeyBoardUtils.closeKeybord(mEditCommentReal, m.mContext);
        mCommentContainer.setVisibility(View.VISIBLE);
        mCommentRealContainer.setVisibility(View.GONE);
        if (clearText) {
            mEditCommentReal.setText("");
            mEditCommentReal.setHint("回复：");
        }
    }

    private void getCourseDetail() {
        GetCourseReq req = new GetCourseReq(mCourseInfo.id);
        Call<GeneralResponse<CourseInfo>> call = mWindowService.getCourseDetail(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<CourseInfo>>() {
            @Override
            public void onResponse(Call<GeneralResponse<CourseInfo>> call, Response<GeneralResponse<CourseInfo>> response) {
                CourseInfo courseInfo = response.body().data;
                mContentFragment.setCourseInfo(courseInfo);
                mReplyFragment.setCourseInfo(courseInfo);
            }

            @Override
            public void onFailure(Call<GeneralResponse<CourseInfo>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(sticky = true)
    public void onGetStickyEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_VIDEO_COURSE_INFO)) {
            this.mCourseInfo = (CourseInfo) event.data;
        }
    }

    @Subscribe
    public void onGetEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_CLOSE_COMMENT)) {
            String comment = mEditCommentReal.getText().toString();
            closeComment(TextUtils.isEmpty(comment));
        }
    }

    @Event(R.id.replies)
    private void showReplyClick(View v) {
        showReply();
    }


    @Event(R.id.send_reply)
    private void replyClick(View v) {
        String comment = mEditCommentReal.getText().toString();
        if (TextUtils.isEmpty(comment)) {
            MyToast.showBlueCircleToast(m.mContext, "请输入评论");
            return;
        }
        InfoReplyReq req = new InfoReplyReq(mCourseInfo.id, m.getLoginResp().userID, comment, 0);
        Call<GeneralResponse<Object>> call = mInfoService.reply(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<Object>>() {
            @Override
            public void onResponse(Call<GeneralResponse<Object>> call, Response<GeneralResponse<Object>> response) {
                GeneralResponse resp = response.body();
                if (resp.result == ResponseCode.SUCCESS) {
                    MyToast.showBlueCircleToast(m.mContext, "评论成功");
                    closeComment(true);
                    mReplyFragment.refreshReplyList();
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<Object>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void initFragments() {
        mContentFragment = new VideoCourseDetailContentFragment();
        mReplyFragment = new VideoCourseDetailReplyFragment();
        mFragments = new Fragment[]{mContentFragment, mReplyFragment};
    }

    private void showContent() {
        if (mContentFragment.isAdded() && mContentFragment.isVisible())
            return;
        if (mReplyFragment.isAdded() && mReplyFragment.isVisible()) {
            getSupportFragmentManager().beginTransaction().hide(mReplyFragment).commit();
            getSupportFragmentManager().beginTransaction().show(mContentFragment).commit();
        } else
            getSupportFragmentManager().beginTransaction().add(R.id.content_container, mContentFragment).commit();
    }

    private void showReply() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mReplyFragment.isAdded() && mReplyFragment.isVisible())
            return;
        transaction.addToBackStack(null);
        if (mContentFragment.isAdded() && mContentFragment.isVisible()) {
            transaction.hide(mContentFragment);
        }
        if (mReplyFragment.isAdded()) {
            transaction.show(mReplyFragment);
        } else
            transaction.add(R.id.content_container, mReplyFragment);
        transaction.commit();
    }

}
